<?php

namespace App\Providers;

use App\Exceptions\Handler;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\ServiceProvider;
use Throwable;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if ($this->app->isLocal()) {
            $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
        }
        if (!$this->app->isProduction()) {
            $this->app->register(\Barryvdh\Debugbar\ServiceProvider::class);
        }

        //修复json系列化小数点溢出
        ini_set('serialize_precision', 14);

        Factory::guessFactoryNamesUsing(
            function ($modelName) {
                return 'Database\\Factories\\'.class_basename($modelName).'Factory';
            }
        );
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // 自定义dingo api异常处理
        app('Dingo\Api\Exception\Handler')->register(
            function (Throwable $exception) {
                return (new Handler($this->app))->render(request(), $exception);
            }
        );
        // dingo api路由频率限制使用自定义规则
        app('Dingo\Api\Http\RateLimit\Handler')->setRateLimiter(
            function ($app, $request) {
                return $app->make(\App\Http\Middleware\ExThrottleRequests::class)->getRateLimiterKey($request);
            }
        );

        if (!$this->app->isProduction()) {
            app('debugbar')->enable();
        }
    }
}
